import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { NextRequest } from 'next/server';

export async function GET() {
  try {
    // 从数据库获取所有敏感词
    const illegalWords = await prisma.illegalWords.findMany({
      orderBy: {
        createDate: 'desc'
      }
    });

    return NextResponse.json({ illegalWords }, { status: 200 });
  } catch (error) {
    console.error('获取敏感词数据失败:', error);
    return NextResponse.json(
      { error: '获取敏感词数据失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { words, isEnable = 1 } = body;

    // 验证必要字段
    if (!words) {
      return NextResponse.json(
        { error: '敏感词内容不能为空' },
        { status: 400 }
      );
    }

    // 检查敏感词是否已存在
    const existingWord = await prisma.illegalWords.findFirst({
      where: { words }
    });

    if (existingWord) {
      return NextResponse.json(
        { error: '该敏感词已存在' },
        { status: 400 }
      );
    }

    // 创建新敏感词
    const newIllegalWord = await prisma.illegalWords.create({
      data: {
        words,
        isEnable,
        createDate: new Date()
      }
    });

    return NextResponse.json({ illegalWord: newIllegalWord }, { status: 201 });
  } catch (error) {
    console.error('创建敏感词失败:', error);
    return NextResponse.json(
      { error: '创建敏感词失败' },
      { status: 500 }
    );
  }
}

export async function PATCH(request: Request) {
  try {
    const body = await request.json();
    const { id, isEnable } = body;

    if (!id) {
      return NextResponse.json(
        { error: '敏感词ID不能为空' },
        { status: 400 }
      );
    }

    // 更新敏感词状态
    const updatedIllegalWord = await prisma.illegalWords.update({
      where: { id: Number(id) },
      data: { isEnable }
    });

    return NextResponse.json({ illegalWord: updatedIllegalWord }, { status: 200 });
  } catch (error) {
    console.error('更新敏感词状态失败:', error);
    return NextResponse.json(
      { error: '更新敏感词状态失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    // 从URL获取敏感词ID
    const id = request.nextUrl.searchParams.get('id');
    
    if (!id) {
      return NextResponse.json(
        { error: '敏感词ID不能为空' },
        { status: 400 }
      );
    }
    
    // 删除敏感词
    await prisma.illegalWords.delete({
      where: { id: Number(id) }
    });
    
    return NextResponse.json(
      { message: '敏感词删除成功' },
      { status: 200 }
    );
  } catch (error) {
    console.error('删除敏感词失败:', error);
    return NextResponse.json(
      { error: '删除敏感词失败' },
      { status: 500 }
    );
  }
}